﻿using AntdUI;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TPressure
{
    public partial class DevicePointForm : BaseForm
    {
        #region 属性
        /// <summary>设备模型
        /// 
        /// </summary>
        public DeviceItem deviceObj;

        /// <summary>设备点位模型
        /// 
        /// </summary>
        private DevicePoint obj;

        #endregion

        #region 自定义方法

        /// <summary>设备点位列表
        /// 
        /// </summary>
        public void LoadDevicePointList()
        {
            Dictionary<string, object> where = new Dictionary<string, object>();
            where["device_number"] = DeviceNumberInput.Text;
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(where);
            UpdateTable(list);
        }

        /// <summary>更新DataGridView
        /// 
        /// </summary>
        /// <param name="list"></param>
        private void UpdateTable(List<DevicePoint> list)
        {
            var antItemList = new List<DevicePointItem>();
            foreach (DevicePoint item in list)
            {
                string range = item.range_min.ToString() + "-" + item.range_max.ToString();
                string outValue = item.out_min.ToString() + "-" + item.out_max.ToString();
                string alarm = item.alarm_hight.ToString() + "-" + item.alarm_low.ToString();
                string registerType = intToRegister(item.register_type);
                
                antItemList.Add(new DevicePointItem(item.device_number, item.device_name, item.point_number,item.point_name,item.point_address,range,outValue,item.amend,alarm,item.error_range,item.unit, registerType));
            }
            Table1.DataSource = antItemList;
        }

        /// <summary>更新模型
        /// 
        /// </summary>
        private void UpdateObject()
        {
            if (obj == null)
            {
                obj = new DevicePoint();
            }
            obj.device_number = DeviceNumberInput.Text.ObjToInt();
            obj.device_name = DeviceNameInput.Text;
            obj.device_address = deviceObj.deviceAddress.ObjToInt();
            obj.point_number = PointNumberInput.Text.ObjToInt();
            obj.point_name = PointNameInput.Text;
            obj.point_address = PointAddressInputNumber.Text.ObjToInt();
            obj.range_min = float.Parse(rangeMinInputNumber.Text);
            obj.range_max = float.Parse(RangeMaxInputNumber.Text);
            obj.out_min = float.Parse(OutMinInputNumber.Text);
            obj.out_max = float.Parse(OutMaxInputNumber.Text);
            obj.amend = float.Parse(AmendInputNumber.Text);
            obj.alarm_hight = float.Parse(AlarmHightInputNumber.Text);
            obj.alarm_low = float.Parse(AlarmLowInputNumber.Text);
            obj.error_range = float.Parse(ErrorRangeInputNumber.Text);
            obj.unit = UnitInput.Text;
            obj.register_type = RegisterTypeToInt(RegisterTypeSelect.Text);
        }

        /// <summary>刷新
        /// 
        /// </summary>
        private void Reload()
        {
            PointNumberInput.Text = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
            obj = null;
            PointNameInput.Text = "";
            PointAddressInputNumber.Text = "";
            rangeMinInputNumber.Text = "";
            RangeMaxInputNumber.Text = "";
            OutMinInputNumber.Text = "";
            OutMaxInputNumber.Text = "";
            AmendInputNumber.Text = "";
            AlarmHightInputNumber.Text = "";
            AlarmLowInputNumber.Text = "";
            ErrorRangeInputNumber.Text = "";
            UnitInput.Text = "";
            RegisterTypeSelect.Text = "";
        }

        /// <summary>重复检测
        /// 
        /// </summary>
        /// <returns></returns>
        private bool CheckRepeat()
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["device_number"] = DeviceNumberInput.Text;
            where["point_name"] = PointNameInput.Text;
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(where);
            int count = list.Count;
            if (count > 0)
            {
                AntdUI.Message.error(this, where["point_name"] + "点位已存在", Font);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>根据编号查询记录
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private DevicePoint DevicePointWithNumber(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["point_number"] = number;
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(where);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>判断记录是否存在
        /// 
        /// </summary>
        /// <param name="number"></param>
        private bool CheckSelectedRowExist(int number)
        {
            obj = DevicePointWithNumber(number);
            if (obj == null)
            {
                Alert.Error("设备点位记录不存在", this);
                return false;
            }
            else
            {
                return true;
            }
        }

        private int RegisterTypeToInt(string typeString)
        {
            int type = 0;
            if (typeString == "DI")
            {
                type = 1;
            }
            else if (typeString == "DO")
            {
                type = 2;
            }
            else if (typeString == "InputRegister")
            {
                type = 3;
            }
            else if (typeString == "HoldingRegister")
            {
                type = 4;
            }
            return type;
        }

        private string intToRegister(int type) 
        {
            string registerType = "";
            if (type == 1)
            {
                registerType = "DI";
            }
            else if (type == 2)
            {
                registerType = "DO";
            }
            else if (type == 3)
            {
                registerType = "InputRegister";
            }
            else if (type == 4)
            {
                registerType = "HoldingRegister";
            }
            return registerType;
        }

        #endregion

        #region 系统方法
        public DevicePointForm()
        {
            InitializeComponent();
        }

        private void DevicePointForm_Load(object sender, EventArgs e)
        {
            RefreshButton_Click(this.RefreshButton, null);

            if (deviceObj.deviceNumber > 0)
            {
                DeviceNumberInput.Text = deviceObj.deviceNumber.ToString();
            }

            if (deviceObj.deviceName.Length > 0)
            {
                DeviceNameInput.Text = deviceObj.deviceName;
            }

            Table1.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("device_number","设备编号"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("device_name","设备名称"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("point_number","点位编号"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("point_name","点位名称"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("point_address","点位地址"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("range","量程范围"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("outValue","输出范围"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("alarm","报警范围"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("error_range","判断范围"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("unit","数据单位"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("register_type","寄存器类型"){ColAlign=AntdUI.ColumnAlign.Center},
                new AntdUI.Column("operation","操作"){ Fixed=true,Width="auto",ColAlign=AntdUI.ColumnAlign.Center}
            };
            Spin.Config config = new Spin.Config
            {
                Text = "正在加载中...",
            };
            Table1.Spin(config, () =>
            {
                LoadDevicePointList();
            }, () =>
            {

            });
        }

        private void Table1_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is DevicePointItem data)
            {
                
                AntdUI.CellLink link = e.Btn;
                if (link.Id == "edit")
                {
                    bool res = CheckSelectedRowExist(data.point_number);
                    if (!res)
                    {
                        return;
                    }
                    PointNumberInput.Text = obj.point_number.ToString();
                    PointNameInput.Text = obj.point_name;
                    PointAddressInputNumber.Text = obj.point_address.ToString();
                    rangeMinInputNumber.Text = obj.range_min.ToString();
                    RangeMaxInputNumber.Text = obj.range_max.ToString();
                    OutMinInputNumber.Text = obj.out_min.ToString();
                    OutMaxInputNumber.Text = obj.out_max.ToString();
                    AmendInputNumber.Text = obj.amend.ToString();
                    AlarmHightInputNumber.Text = obj.alarm_hight.ToString();
                    AlarmLowInputNumber.Text = obj.alarm_low.ToString();
                    ErrorRangeInputNumber.Text = obj.error_range.ToString();
                    UnitInput.Text = obj.unit;
                    string register_type = intToRegister(obj.register_type);
                    RegisterTypeSelect.Text = register_type;                
                }
                else if (link.Id == "delete")
                {
                    AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", "您确定要删除此点位吗？")
                    {
                        OnOk = config =>
                        {
                            bool res = CheckSelectedRowExist(data.point_number);
                            if (!res)
                            {
                                return true;
                            }
                            List<DevicePoint> list = new List<DevicePoint>();
                            list.Add(obj);
                            int deleteRes = SqlSugarHelper.Deleteable(list);
                            if (deleteRes > 0)
                            {
                                RefreshButton_Click(this.RefreshButton, null);
                            }
                            else
                            {
                                Alert.Error("删除设备失败", this);
                            }
                            return true;
                        },
                    });
                }
            }
        }
        #endregion

        #region 点击按钮
        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            if (obj != null )
            {
                if (PointNameInput.Text != obj.point_name)
                {
                    bool repeatRes = CheckRepeat();
                    if (repeatRes)
                    {
                        return;
                    }
                }
                UpdateObject();
                List<DevicePoint> list = new List<DevicePoint>();
                list.Add(obj);
                int res = SqlSugarHelper.Updateable<DevicePoint>(list);
                if (res > 0)
                {
                    RefreshButton_Click(this.RefreshButton, null);
                }
                else
                {
                    Alert.Error("编辑设备点位失败", this);
                }
            }
            else
            {
                if (PointNameInput.Text.Length == 0)
                {
                    Alert.Error("请输入点位名称", this);
                    DeviceNameInput.Focus();
                    return;
                }

                if (PointAddressInputNumber.Text.Length == 0)
                {
                    Alert.Error("请输入点位地址", this);
                    DeviceNameInput.Focus();
                    return;
                }

                bool repeatRes = CheckRepeat();
                if (repeatRes)
                {
                    return;
                }
                UpdateObject();
                List<DevicePoint> list = new List<DevicePoint>();
                list.Add(obj);
                int res = SqlSugarHelper.Insertable(list);
                if (res > 0)
                {
                    RefreshButton_Click(this.RefreshButton, null);
                }
                else
                {
                    Alert.Error("添加设备点位失败", this);
                }
            }
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            Reload();
            Task.Run(() =>
            {
                LoadDevicePointList();
            });
        }

        #endregion
    }
}
